package com.itheima.case2.service;

import com.itheima.case2.dao.CaseDao;
import com.itheima.case2.pojo.po.Role;
import com.itheima.case2.pojo.po.User;
import com.itheima.case2.pojo.vo.AddUser;
import com.itheima.case2.pojo.vo.PageResult;
import com.itheima.case2.pojo.vo.QueryPageBean;
import com.itheima.case2.pojo.vo.UpdateUser;
import com.itheima.case2.utils.SqlSessionUtil;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;

import java.util.List;


/**
 * @author user
 */
public class CaseServcie {


    public PageResult findAllByPage(QueryPageBean queryPageBean){
        SqlSession session = SqlSessionUtil.getSession();
        CaseDao mapper = session.getMapper(CaseDao.class);
        Integer index1=1;
        Integer count1=5;
        Integer offset = queryPageBean.getOffset();
        if(queryPageBean.getCurrentPage()==null){
            queryPageBean.setCurrentPage(index1);
        }
        if(queryPageBean.getPageSize()==null){
            queryPageBean.setPageSize(count1);
        }
        List<User> allByPage = mapper.findAllByPage(queryPageBean);
        Long sum = mapper.findSum(queryPageBean);//数据总数
        session.close();
        PageResult pageResult=new PageResult(sum,allByPage);
        return pageResult;
    }


    public List<Role> findRoles(){
        SqlSession session = SqlSessionUtil.getSession();
        CaseDao mapper = session.getMapper(CaseDao.class);
        List<Role> roles = mapper.findRoles();
        session.close();
        return  roles;
    }

    public void addRoleUser(AddUser addUser){
        SqlSession sqlSession=SqlSessionUtil.getSession();
        CaseDao mapper = sqlSession.getMapper(CaseDao.class);
//        主键回写,把数据存入数据库后返回主键映射到addUser的id中
        mapper.addUser(addUser);
        mapper.addRoleUser(addUser.getId(),addUser.getRoleIds());
        sqlSession.close();
    }


    /**
     * 多表修改数据
     */
    public void update(UpdateUser updateUser){
        SqlSession session = SqlSessionUtil.getSession();
        CaseDao mapper = session.getMapper(CaseDao.class);
        mapper.updateUser(updateUser);
        mapper.deltdRoles(updateUser.getId());
        mapper.updateRoles(updateUser.getId(),updateUser.getRoleIds());
        session.close();
    }


    /**
     * 多表删除
     */

    public void delete(Integer u_id){
        SqlSession session = SqlSessionUtil.getSession();
        CaseDao mapper = session.getMapper(CaseDao.class);
//        根据用户id删除中间用户所对应的角色
        mapper.deltdRoles(u_id);
//        根据用户id删除所所有的用户信息
        mapper.delById(u_id);
        session.close();
    }

}
